<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import {
  Tickets,
  List,
  Location,
  Van,
  Grid,
  User,
  SwitchButton,
  DataAnalysis,
  Document,
  Fold,
  Expand,
  HomeFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const isCollapsed = ref(false)

// 路由元信息映射
const routeTitleMap: Record<string, string> = {
  '/purchase': '购票大厅',
  '/orders': '我的订单',
  '/stations': '车站管理',
  '/trains': '车次管理',
  '/carriages': '车厢管理',
  '/ticket-management': '票务管理',
  '/users': '用户中心',
  '/statistics': '数据看板'
}

// 面包屑导航
const breadcrumbs = computed(() => {
  const paths: Array<{ title: string; path: string }> = [
    { title: '首页', path: '/' }
  ]

  if (route.path !== '/login' && route.path !== '/') {
    const title = routeTitleMap[route.path] || route.meta.title as string
    if (title) {
      paths.push({ title, path: route.path })
    }
  }

  return paths
})

const handleMenuSelect = (key: string) => {
  router.push(key)
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
}

const showLayout = computed(() => {
  return route.path !== '/login'
})

// 获取用户角色徽章
const userRoleBadge = computed(() => {
  return userStore.isAdmin() ? '管理员' : '普通用户'
})

const userRoleType = computed(() => {
  return userStore.isAdmin() ? 'danger' : 'success'
})

onMounted(() => {
  userStore.restoreUser()
})
</script>

<template>
  <div class="app-container">
    <!-- 登录页面不显示布局 -->
    <router-view v-if="!showLayout" />

    <!-- 主应用布局 -->
    <el-container v-else class="main-layout">
      <!-- 侧边栏 -->
      <el-aside :width="isCollapsed ? '64px' : '240px'" class="sidebar">
        <!-- Logo 区域 -->
        <div class="logo-container">
          <transition name="fade">
            <div v-if="!isCollapsed" class="logo-content">
              <div class="logo-icon">🚄</div>
              <div class="logo-text">
                <h2>火车票售票系统</h2>
                <p>Railway Ticket System</p>
              </div>
            </div>
            <div v-else class="logo-collapsed">🚄</div>
          </transition>
        </div>

        <!-- 菜单区域 -->
        <el-menu
          :default-active="$route.path"
          :collapse="isCollapsed"
          class="sidebar-menu"
          @select="handleMenuSelect"
          router
        >
          <!-- 用户功能区（所有用户可见） -->
          <el-menu-item index="/purchase">
            <el-icon><Tickets /></el-icon>
            <template #title>购票大厅</template>
          </el-menu-item>

          <el-menu-item index="/orders">
            <el-icon><List /></el-icon>
            <template #title>我的订单</template>
          </el-menu-item>

          <!-- 管理功能区（管理员可见） -->
          <template v-if="userStore.isAdmin()">
            <!-- 运营中心 - 子菜单 -->
            <el-sub-menu index="operations">
              <template #title>
                <el-icon><Van /></el-icon>
                <span>运营中心</span>
              </template>
              <el-menu-item index="/stations">
                <el-icon><Location /></el-icon>
                <template #title>车站管理</template>
              </el-menu-item>
              <el-menu-item index="/trains">
                <el-icon><Van /></el-icon>
                <template #title>车次管理</template>
              </el-menu-item>
              <el-menu-item index="/carriages">
                <el-icon><Grid /></el-icon>
                <template #title>车厢管理</template>
              </el-menu-item>
              <el-menu-item index="/ticket-management">
                <el-icon><Document /></el-icon>
                <template #title>票务管理</template>
              </el-menu-item>
            </el-sub-menu>

            <!-- 数据看板 -->
            <el-menu-item index="/statistics">
              <el-icon><DataAnalysis /></el-icon>
              <template #title>数据看板</template>
            </el-menu-item>

            <!-- 用户中心 -->
            <el-menu-item index="/users">
              <el-icon><User /></el-icon>
              <template #title>用户中心</template>
            </el-menu-item>
          </template>
        </el-menu>

        <!-- 折叠按钮 -->
        <div class="sidebar-footer">
          <el-button
            :icon="isCollapsed ? Expand : Fold"
            @click="toggleSidebar"
            type="info"
            text
            class="collapse-btn"
          >
            {{ isCollapsed ? '' : '收起' }}
          </el-button>
        </div>
      </el-aside>

      <!-- 主内容区 -->
      <el-container class="content-wrapper">
        <!-- 顶部导航栏 -->
        <el-header class="app-header">
          <div class="header-left">
            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/" class="breadcrumb">
              <el-breadcrumb-item
                v-for="(item, index) in breadcrumbs"
                :key="index"
                :to="index === 0 ? (userStore.isAdmin() ? '/trains' : '/purchase') : item.path"
              >
                <el-icon v-if="index === 0"><HomeFilled /></el-icon>
                <span v-else>{{ item.title }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <!-- 用户信息卡片 -->
            <div class="user-info-card">
              <div class="user-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div class="user-details">
                <div class="user-name">{{ userStore.currentUser?.realName }}</div>
                <el-tag :type="userRoleType" size="small" class="user-role">
                  {{ userRoleBadge }}
                </el-tag>
              </div>
            </div>

            <!-- 退出按钮 -->
            <el-button
              type="danger"
              :icon="SwitchButton"
              @click="handleLogout"
              class="logout-btn"
            >
              退出登录
            </el-button>
          </div>
        </el-header>

        <!-- 主内容区 -->
        <el-main class="main-content">
          <transition name="fade-slide" mode="out-in">
            <router-view />
          </transition>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.app-container {
  height: 100vh;
  overflow: hidden;
}

.main-layout {
  height: 100%;
}

/* ==================== 侧边栏样式 ==================== */

.sidebar {
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #2C3E50 0%, #1E293B 100%);
  transition: width var(--transition-base);
}

.logo-container {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-4);
  background: linear-gradient(135deg, var(--primary-dark), var(--secondary-dark));
  position: relative;
  overflow: hidden;
}

.logo-container::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: breathing 4s ease-in-out infinite;
}

.logo-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
  position: relative;
  z-index: 1;
}

.logo-icon {
  font-size: 2rem;
  animation: pulse 2s ease-in-out infinite;
}

.logo-text h2 {
  margin: 0;
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-bold);
  color: var(--text-inverse);
  line-height: 1.2;
}

.logo-text p {
  margin: 0;
  font-size: var(--font-size-xs);
  color: rgba(255, 255, 255, 0.8);
  font-weight: var(--font-weight-light);
}

.logo-collapsed {
  font-size: 2rem;
  animation: pulse 2s ease-in-out infinite;
}

.sidebar-menu {
  flex: 1;
  border-right: none;
  background: transparent;
  overflow-y: auto;
  padding: var(--spacing-2) 0;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 240px;
}

.sidebar-footer {
  padding: var(--spacing-4);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  justify-content: center;
}

.collapse-btn {
  width: 100%;
  color: rgba(255, 255, 255, 0.8);
  font-weight: var(--font-weight-medium);
}

.collapse-btn:hover {
  color: var(--text-inverse);
  background: rgba(255, 255, 255, 0.1);
}

/* ==================== 头部样式 ==================== */

.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--bg-primary);
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--shadow-sm);
  padding: 0 var(--spacing-6);
  height: 64px;
}

.header-left {
  flex: 1;
}

.breadcrumb {
  font-size: var(--font-size-sm);
}

.header-right {
  display: flex;
  align-items: center;
  gap: var(--spacing-4);
}

/* 用户信息卡片 */
.user-info-card {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
  padding: var(--spacing-2) var(--spacing-4);
  background: var(--gradient-soft);
  border-radius: var(--radius-lg);
  transition: all var(--transition-base);
  cursor: pointer;
}

.user-info-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: var(--radius-full);
  background: var(--gradient-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-inverse);
  font-size: var(--font-size-xl);
  box-shadow: var(--shadow-sm);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-1);
}

.user-name {
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  line-height: 1;
}

.user-role {
  font-size: var(--font-size-xs);
}

.logout-btn {
  border-radius: var(--radius-base);
  font-weight: var(--font-weight-medium);
}

/* ==================== 主内容区样式 ==================== */

.content-wrapper {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  background: var(--bg-secondary);
  padding: var(--spacing-6);
}

/* ==================== 动画效果 ==================== */

.fade-enter-active,
.fade-leave-active {
  transition: opacity var(--transition-base);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-slide-enter-active {
  transition: all var(--transition-base);
}

.fade-slide-leave-active {
  transition: all var(--transition-fast);
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

/* ==================== 响应式适配 ==================== */

@media (max-width: 768px) {
  .app-header {
    padding: 0 var(--spacing-4);
  }

  .user-details {
    display: none;
  }

  .breadcrumb {
    font-size: var(--font-size-xs);
  }

  .main-content {
    padding: var(--spacing-4);
  }
}
</style>
